package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserReportVO;
import com.sky.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    /*
     * 微信登录
     * */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 调用方法获得openid
        String openId = getOpenId(userLoginDTO);

        // 判断openid是否存在，不存在抛异常
        if (openId == null){
            throw new LoginFailedException(openId);
        }
        // 判断用户是否为新用户,如果是新用户则自动创建
        User user = userMapper.selectByOpenId(openId);

        if (user == null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        // 返回user对象

        return user;
    }



    private String getOpenId(UserLoginDTO userLoginDTO) {
        // 调用微信服务器接口获得用户的openid
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", userLoginDTO.getCode());
        params.put("grant_type", "authorization_code");

        // openid在返回的响应体中
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, params);
        // 解析接受的响应体
        JSONObject jsonObject = JSONObject.parseObject(json);
        return jsonObject.getString("openid");
    }
}
